package com.hengxinguotong.hxgtwygsp.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import java.util.Iterator;
import java.util.Map;

/**
 * @author Administrator
 * @function
 * @date 2017/4/1
 */
public class PreferencesUtil
{
    private static final String NAME = "HXGTWYGLJ";
    private SharedPreferences mPreferences;

    public PreferencesUtil(Context context)
    {
        mPreferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
    }

    /**
     * 保存一组信息
     *
     * @param key
     * @param value
     * @return void
     * @author hjz
     * @since 2018/12/22 11:18
     */
    public <T> void saveData(String key, T value)
    {
        SharedPreferences.Editor editor = mPreferences.edit();
        if (value instanceof String)
        {
            editor.putString(key, (String) value);
        } else if (value instanceof Integer)
        {
            editor.putInt(key, (Integer) value);
        } else if (value instanceof Boolean)
        {
            editor.putBoolean(key, (Boolean) value);
        } else if (value instanceof Long)
        {
            editor.putLong(key, (Long) value);
        } else
        {
            Log.e(NAME, "数据不合法");
        }
        editor.apply();
    }

    /**
     * 保存多组信息
     *
     * @param map
     * @return void
     * @author hjz
     * @since 2018/12/22 11:27
     */
    public void saveDatas(Map<String, String> map)
    {
        SharedPreferences.Editor editor = mPreferences.edit();
        Iterator<String> iterator = map.keySet().iterator();
        String key;
        while (iterator.hasNext())
        {
            key = iterator.next();
            editor.putString(key, map.get(key));
        }
        editor.apply();
    }

    /**
     * 查询某个KEY对应的VALUE
     *
     * @param key
     * @return java.lang.String
     * @author hjz
     * @since 2018/12/22 11:28
     */
    public String queryData(String key)
    {
        return mPreferences.getString(key, null);
    }

    /**
     * 是否包含某个KEY
     *
     * @param key
     * @return boolean
     * @author hjz
     * @since 2018/12/22 11:28
     */
    public boolean contain(String key)
    {
        return mPreferences.contains(key);
    }

    /**
     * 删除某个KEY
     *
     * @param key
     * @return void
     * @author hjz
     * @since 2018/12/22 11:29
     */
    public void remove(String key)
    {
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.remove(key);
        editor.apply();
    }

    /**
     * 清除所有的信息
     *
     * @return void
     * @author hjz
     * @since 2018/12/22 11:29
     */
    public void clear()
    {
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.clear();
        editor.apply();
    }
}
